import json
from TwoApp.libs.captcha.captcha import captcha
from django.views import View
from django.http import HttpResponse, HttpResponseBadRequest
from random import randint

from django_redis import get_redis_connection
from TwoApp import models


'''
1、登录
2、注册
3、验证码
'''

#注册用户信息
class RigisterView(View):
    @staticmethod
    def post(request):
        rigisterData = json.loads(request.body)
        print(rigisterData)
        username = rigisterData['username']
        passwd = rigisterData['pass']
        checkpasswd = rigisterData['checkPass']
        mail = rigisterData['mail']

        register = models.TwoRegister.objects.create(username= username,passwd = passwd,checkpasswd= checkpasswd,mail=mail)
        if (register):
            return HttpResponse("register success")
        else:
            return HttpResponse("register Error")

#用户登录
class loginView(View):
    @staticmethod
    def post(request):
        loginData = json.loads(request.body)
        print(loginData)
        username = loginData['username']
        passwd = loginData['password']

        userlogin = models.TwoRegister.objects.filter(username= username,passwd = passwd)
        
        if userlogin:
            return HttpResponse("login Success")
        else:
            return HttpResponse("login Error")

#用户注册时间和上次登录时间和地址


        
#创建验证码图片
class CaptchaView(View):
    @staticmethod
    def get(request):
        uuid = request.GET.get('uuid')
        # # 判断uuid是否存在
        if uuid is None:
            return HttpResponseBadRequest("验证码有误!")
        # 通过验证码库生成验证码
        text, image = captcha.generate_captcha()
        # # 链接redis
        redis_conn = get_redis_connection("default")
        # # 存入redis过期时间
        redis_conn.set("img:%s" % uuid, text, 300)
        
        return HttpResponse(image, content_type="image/jpeg")


#校验验证码
class ImgCheckCode(View):
    @staticmethod
    def get(request):
        # 获取用户输入的code
        uuid = request.GET.get('uuid')
    
        # 链接redis
        redisConn = get_redis_connection("default")
        # 获取存入redis的验证码key值,有效时间为300秒
        code = (redisConn.get("img:%s" % uuid))
        print(code)
        # 获取uuid对应的验证码
        return HttpResponse(code)
